"use strict";

//requires
var glob   = require('glob');
var path   = require('path');

//require koa and koa middleware
var koa     = require('koa');
var router  = require('koa-router');
var render  = require('koa-ejs');
var mstatic = require('koa-static');

var app    = koa();

app.name = 'LeoServer';
app.proxy = true;

var isDev = process.env.NODE_ENV !== 'PRODUCT';

if(isDev){
  // log server response time
  app.use(function *(next){
    var start = new Date();
    yield next;
    var ms = new Date() - start;
    console.log('%s %s - %s', this.method, this.url, ms);
  });
}

//setup view
var filters = {
  format: function (time) {
    return time.getFullYear() + '-' + time.getMonth() + 1 + '-' + time.getDate();
  }
};

render(app, {
  root    : path.join(__dirname, 'app', 'view'),
  layout  : false,
  viewExt : 'ejs',
  cache   : isDev,
  debug   : !isDev,
  filters : filters
});


//static
var staticPath = path.join(__dirname, 'static');
console.log('Set static file path to ' + staticPath);
app.use(mstatic(staticPath, {
  maxage: 30*1000
}));

//load router
app.use(router(app));

var routerGlob = path.join(__dirname, 'app', '/router/*Router.js');
var routers = glob.sync(routerGlob);

for(let router of routers){
  require(router)(app);
  console.log('Loaded Router:' + router);
}

app.all(/.*/, function *(){
  yield this.render('404', { path: this.url });
  this.status = 404;
});

app.on('error', function(err, ctx){
  console.log('ServerError', err, ctx);
});

app.listen(9999);
